package cn.btks.databasehandler.handle.controller;

import cn.btks.commonserver.result.MenuSourceEnum;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.result.SystemLogEnum;
import cn.btks.commonserver.valid.SystemLog;
import cn.btks.databasehandler.handle.dto.ResumeBackUpListDto;
import cn.btks.databasehandler.handle.pojo.BackUpConfig;
import cn.btks.databasehandler.handle.service.BackUpConfigService;
import cn.btks.databasehandler.handle.util.QuartzUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author lijun
 * @Date 2020/12/28 17:39
 */
@RestController
@RequestMapping("api/v1.0/backUpConfig")
@Api(tags = "备份配置模块")
@Validated
public class BackUpConfigController {

    @Autowired
    BackUpConfigService backUpConfigService;

    @Autowired
    Scheduler scheduler;

    @SystemLog(type = SystemLogEnum.QUERY_LOG,moduleMessage = MenuSourceEnum.MENU_DATABASE)
    @GetMapping("/findPages")
    @ApiOperation("分页查询备份配置信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNumber", value = "当前页码", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页行数", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "configName", value = "配置名称（模糊查询）", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "configMode", value = "配置类型（0：按照库进行备份 1：按照表进行备份）", required = false, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "configCycle", value = "备份周期（0：年/次 1：半年/次 2：月/次 9：其他）", required = false, dataType = "int"),
            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState findPagesByConfigNameAndConfigModeAndConfigCycle(Integer pageNumber, Integer pageSize,String configName, Integer configMode, Integer configCycle) {
        return backUpConfigService.findPagesByConfigNameAndConfigModeAndConfigCycle(pageNumber, pageSize, configName, configMode, configCycle);
    }

    @SystemLog(type = SystemLogEnum.SAVE_LOG,moduleMessage = MenuSourceEnum.MENU_DATABASE)
    @PostMapping("/save")
    @ApiOperation(value = "新增备份配置信息", notes = "新增备份配置信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "configName", value = "配置名称", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "backUpMode", value = "备份方式（0：按照库进行备份 1：按照表进行备份）", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "selectDBName", value = "选择备份的库的名称", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "selectTableName", value = "若按照表进行备份，则此字段存储选中的数据表（多个表用‘;’进行分割）", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "description", value = "选择数据库或表的描述", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "backUpCycle", value = "备份周期（0：年/次 1：半年/次 2：月/次 9：其他）", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "weekDay", value = "备份周期为周/次时，传值1-7过来", required = false, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "startDate", value = "备份开始日期", required = true, dataType = "date"),
            @ApiImplicitParam(paramType = "query", name = "endDate", value = "备份截止日期", required = true, dataType = "date"),
            @ApiImplicitParam(paramType = "query", name = "startTime", value = "备份开始时间", required = true, dataType = "time"),
            @ApiImplicitParam(paramType = "query", name = "backUpCron", value = "定时任务的cron", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "remark", value = "备份说明", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "createdUserId", value = "创建人ID", required = false, dataType = "long"),
            @ApiImplicitParam(paramType = "query", name = "isStarted", value = "是否启动(0：暂停 1：启动)", required = false, dataType = "int"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState save(@RequestBody BackUpConfig backUpConfig,HttpServletRequest request) throws Exception {
        return backUpConfigService.save(backUpConfig,request);
    }

    @SystemLog(type = SystemLogEnum.UPDATE_LOG,moduleMessage = MenuSourceEnum.MENU_DATABASE)
    @PutMapping("/update")
    @ApiOperation(value = "修改备份配置信息", notes = "修改备份配置信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "配置ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "query", name = "configName", value = "配置名称", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "backUpMode", value = "备份方式（0：按照库进行备份 1：按照表进行备份）", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "selectDBName", value = "选择备份的库的名称", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "selectTableName", value = "若按照表进行备份，则此字段存储选中的数据表（多个表用‘;’进行分割）", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "description", value = "选择数据库或表的描述", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "weekDay", value = "备份周期为周/次时，传值1-7过来", required = false, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "backUpCycle", value = "备份周期（0：年/次 1：半年/次 2：月/次 9：其他）", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "startDate", value = "备份开始日期", required = true, dataType = "date"),
            @ApiImplicitParam(paramType = "query", name = "endDate", value = "备份截止日期", required = true, dataType = "date"),
            @ApiImplicitParam(paramType = "query", name = "startTime", value = "备份开始时间", required = true, dataType = "time"),
            @ApiImplicitParam(paramType = "query", name = "backUpCron", value = "定时任务的cron", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "remark", value = "备份说明", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "createdUserId", value = "创建人ID", required = false, dataType = "long"),
            @ApiImplicitParam(paramType = "query", name = "isStarted", value = "是否启动(0：暂停 1：启动)", required = false, dataType = "int"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState update(@RequestBody BackUpConfig backUpConfig, HttpServletRequest request) throws Exception {
        return backUpConfigService.update(backUpConfig, request);
    }

    @SystemLog(type = SystemLogEnum.UPDATE_LOG,moduleMessage = MenuSourceEnum.MENU_DATABASE)
    @GetMapping("/updateStartStatus/{id}/{isStarted}")
    @ApiOperation(value = "是否启动备份配置", notes = "是否启动备份配置")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "备份配置ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "path", name = "isStarted", value = "是否启动(0：暂停 1：启动)", required = true, dataType = "int"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState updateStartStatus(@PathVariable("id") Long id,@PathVariable("isStarted") Integer isStarted) {
        int result = backUpConfigService.updateIsStarted(id, isStarted);
        if(result > 0){
            BackUpConfig backUpConfig = backUpConfigService.findById(id);
            if(isStarted.equals(0)){
                QuartzUtil.pauseScheduleJob(scheduler,backUpConfig.getConfigName());
                return result > 0 ? new ResultState(StateInfo.PAUSE_OK.getCode(), StateInfo.PAUSE_OK.getMsg(), result) :
                        new ResultState(StateInfo.PAUSE_ERROR.getCode(), StateInfo.PAUSE_ERROR.getMsg());
            }else {
                QuartzUtil.resumeScheduleJob(scheduler,backUpConfig.getConfigName());
            }
        }
        return result > 0 ? new ResultState(StateInfo.START_OK.getCode(), StateInfo.START_OK.getMsg(), result) :
                new ResultState(StateInfo.START_ERROR.getCode(), StateInfo.START_ERROR.getMsg());
    }

    @SystemLog(type = SystemLogEnum.UPDATE_LOG,moduleMessage = MenuSourceEnum.MENU_DATABASE)
    @GetMapping("/startOnce/{id}")
    @ApiOperation(value = "立即启动一次备份", notes = "立即启动一次备份")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "备份配置ID", required = true, dataType = "long"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState updateStartStatus(@PathVariable("id") Long id) {
        BackUpConfig backUpConfig = backUpConfigService.findById(id);
        if(backUpConfig != null){
            QuartzUtil.runOnce(scheduler,backUpConfig.getConfigName());
        }
        return backUpConfig != null ? new ResultState(StateInfo.START_OK.getCode(), StateInfo.START_OK.getMsg()) :
                new ResultState(StateInfo.START_ERROR.getCode(), StateInfo.START_ERROR.getMsg());
    }

    @SystemLog(type = SystemLogEnum.UPDATE_LOG,moduleMessage = MenuSourceEnum.MENU_DATABASE)
    @PostMapping("/startOnce")
    @ApiOperation(value = "立即启动一次备份", notes = "立即启动一次备份（备份文件ID列表）")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "backUpIdList", value = "备份文件ID列表", required = true, dataType = "long"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState updateStartStatus(@RequestBody ResumeBackUpListDto resumeBackUpListDto) {
        List<Long> backUpIdList = resumeBackUpListDto.getBackUpIdList();
        if(backUpIdList != null && backUpIdList.size() > 0){
            for (Long id : backUpIdList){
                BackUpConfig backUpConfig = backUpConfigService.findById(id);
                if(backUpConfig != null){
                    QuartzUtil.runOnce(scheduler,backUpConfig.getConfigName());
                }
                return backUpConfig != null ? new ResultState(StateInfo.START_OK.getCode(), StateInfo.START_OK.getMsg()) :
                        new ResultState(StateInfo.START_ERROR.getCode(), StateInfo.START_ERROR.getMsg());
            }
        }
        return new ResultState(StateInfo.START_ERROR.getCode(), StateInfo.START_ERROR.getMsg());
    }

    @SystemLog(type = SystemLogEnum.DELETE_LOG,moduleMessage = MenuSourceEnum.MENU_DATABASE)
    @DeleteMapping("/delete/{id}")
    @ApiOperation("根据ID删除备份配置信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "配置ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "header", name = "token", value = "token密匙", required = true, dataType = "string")
    })
    public ResultState delete(@PathVariable("id") Long id) {
        return backUpConfigService.delete(id);
    }
}